/**
 * Constructs and displays a table containing user-saved workouts.
 * It also sorts the displayed workouts by name, recorded time, and 
 * the calendar day when a workout was saved.
 * @author Diego Galaz
 * 
 */

package eft.android.view;

import java.util.ArrayList;
import java.util.List;

import me.croute.calendarexample.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import eft.android.controller.Controller;
import eft.android.controller.Workout;

public class ExerciseHistory extends Activity {
	
	private TableLayout exercises_table;
	private Controller controller = new Controller();
	private List<Workout> workoutList;

	// This array is used only for demonstration purposes
	public static String[] girls = { "Fran", "Diane", "Elizabeth",
		"Angie", "Barbara", "Chelsea", "Cindy", "Grace", "Helen",
		"Isabel", "Jackie", "Karen", "Linda", "Mary", "Nancy" };
	
	// This array is used only for demonstration purposes
	public static String[] girlsSorted = { "Angie", "Barbara", "Chelsea", 
		"Cindy", "Diane", "Elizabeth", "Fran", "Grace", "Helen", 
		"Isabel", "Jackie", "Karen", "Linda", "Mary", "Nancy"  };
	
	// This array is used only for demonstration purposes
	public static String[] nums = { "2012/01/05", "2012/01/07", "2012/01/10", 
		"2012/01/20", "2012/01/28", "2012/02/04", "2012/02/10", "2012/02/11", 
		"2012/01/20", "2012/01/28", "2012/02/04", "2012/02/10", "2012/02/11",
		"2012/01/20", "2012/01/28" };
	
	// This array is used only for demonstration purposes
	public static String[] times = { "10:42", "1:43", "11:43", "11:43",
		"11:43", "11:43", "11:43", "11:43", "11:43", "1:43", "11:43",
		"11:43", "11:43", "11:43", "11:43" };
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	try {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.exercisehistory);
            
            exercises_table = (TableLayout) findViewById(R.id.exercises_table);
            
            Button back = (Button) findViewById(R.id.back_button);
            Button date = (Button) findViewById(R.id.date_sort_button);
            Button name = (Button) findViewById(R.id.name_sort_button);
            Button time = (Button) findViewById(R.id.time_sort_button);
            
            // Set on-click listeners for each button 
            back.setOnClickListener(onBackButton);
            date.setOnClickListener(onDateButton);
            name.setOnClickListener(onNameButton);
            time.setOnClickListener(onTimeButton);
            
            // Display exercises sorted alphabetically by default
            fillExerciseTableSortedByDate();
    	}
    	catch (Exception e) {
			Log.e("ERROR", "ERROR IN CODE: " + e.toString());
			e.printStackTrace();
		}
    }
    
    /** Creates a click listener for Back button */
    private View.OnClickListener onBackButton = new View.OnClickListener() {
		
		public void onClick(View v) {
			 Intent backToCalendar = new Intent(getApplicationContext(), CalendarViewActivity.class);
			 startActivity(backToCalendar);
		}
	};
    
    /** Creates a click listener for Date sort button */
    private View.OnClickListener onDateButton = new View.OnClickListener() {
		
		public void onClick(View v) {
			fillExerciseTableSortedByDate();			
		}
	};
    
	/** Creates a click listener for Alphabetical sort button */
	private View.OnClickListener onNameButton = new View.OnClickListener() {
		
		public void onClick(View v) {
			fillExerciseTableSortedByName();
		}
	};
	
	/** Creates a click listener for Date sort button */
	private View.OnClickListener onTimeButton = new View.OnClickListener() {
		
		public void onClick(View v) {
			fillExerciseTableSortedByTime();
		}
	};
    
    /**
     * Dynamically creates a table listing the exercise history of the user.
     * @param None
     * @return None
     */
    private void fillExerciseTableSortedByTime() {
    	
    	TableRow row;
    	TextView t1, t2, t3;
    	
    	// Clear the table. seemingly unnecessary steps below assure clearing of table, when 
    	// there is only one item left in the table.
		exercises_table.removeAllViewsInLayout();
		row = new TableRow(this);
		exercises_table.addView(row, new TableLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

    	// Clear the table from previous data 
    	exercises_table.removeAllViewsInLayout();
    	
    	try {
    		workoutList = new ArrayList<Workout>(controller.getAllUserWorkouts());
    	} catch (Exception e){
    		Toast.makeText(this, "No workouts have been added", Toast.LENGTH_LONG).show();
    		return;
    	}
    	
    	exercises_table.removeAllViewsInLayout();
    	
    	// Sort the workout list by time
    	workoutList = controller.timeOrder(workoutList);
    	
    	// Fill out the exercise history table    	
    	for (int i = 0; i < workoutList.size(); i++) {
    		row = new TableRow(this);
    		
    		t1 = new TextView(this);
    		t2 = new TextView(this);
    		t3 = new TextView(this);
    		
    		if( workoutList.get(i).getTitle().length() > 20 ){
    			t1.setText(workoutList.get(i).getTitle().substring(0, 20) + "... " );
    		}
    		else{ t1.setText(workoutList.get(i).getTitle() ); }
    		
    		// TODO: Convert the date from a long number to MM/DD/YYYY
    		t2.setText(workoutList.get(i).getDateReadable());
    		
    		// TODO: Convert time from seconds to HH:MM:SS
    		//t3.setText(workoutList.get(i).getTimeReadable);
    		t3.setText("" + workoutList.get(i).getTimeReadable() );
    		//t1.setTextSize(20);
    		//t2.setTextSize(20);
    		
    		row.addView(t1);
    		row.addView(t2);
    		row.addView(t3);
    		
    		// Assign the loop counter value as a new id number for each row
    		row.setId(i);

    		exercises_table.addView(row, new TableLayout.LayoutParams(
    				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    		
    		row.setOnClickListener(new  OnClickListener() {
    			// Row was selected
    	        public void onClick(View v) {
    	            v.setBackgroundColor(Color.DKGRAY);
    	            displayWorkoutDetails(v.getId());
    	        }
    	    });
    	}
    }
    
    /**
     * 
     */
    private void fillExerciseTableSortedByDate() {
    	TableRow row;
    	TextView t1, t2, t3;
    	
    	// Clear the table. seemingly unnecessary steps below assure clearing of table, when 
    	// there is only one item left in the table.
		exercises_table.removeAllViewsInLayout();
		row = new TableRow(this);
		exercises_table.addView(row, new TableLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		
		
    	try {
    		workoutList = new ArrayList<Workout>(controller.getAllUserWorkouts());
    		
    	} catch (Exception e){
    		Toast.makeText(this, "No workouts have been added", Toast.LENGTH_LONG).show();
    		return;
    	}
    	
    	exercises_table.removeAllViewsInLayout();
    	
    	// Sort the workout list by date
    	workoutList = controller.dateOrder(workoutList);
    	 	
    	// Fill out the exercise history table    	
    	for (int i = 0; i < workoutList.size(); i++) {
    		row = new TableRow(this);
    		
    		t1 = new TextView(this);
    		t2 = new TextView(this);
    		t3 = new TextView(this);
    		
    		if( workoutList.get(i).getTitle().length() > 20 ){
    			t1.setText(workoutList.get(i).getTitle().substring(0, 20) + "... " );
    		}
    		else{ t1.setText(workoutList.get(i).getTitle() ); }
    		
    		// TODO: Convert the date from a long number to MM/DD/YYYY
    		t2.setText(workoutList.get(i).getDateReadable());
    		
    		// TODO: Convert time from seconds to HH:MM:SS
    		t3.setText(workoutList.get(i).getTimeReadable());
    		
    		//t1.setTextSize(20);
    		//t2.setTextSize(20);
    		
    		row.addView(t1);
    		row.addView(t2);
    		row.addView(t3);
    		
    		// Assign the loop counter value as a new id number for each row
    		row.setId(i);

    		exercises_table.addView(row, new TableLayout.LayoutParams(
    				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    		
    		row.setOnClickListener(new  OnClickListener() {
    			// Row was selected
    	        public void onClick(View v) {
    	            v.setBackgroundColor(Color.DKGRAY);
    	            displayWorkoutDetails(v.getId());
    	        }
    	    });
    	}
    }
    
    /**
     * 
     */
    private void fillExerciseTableSortedByName() {
    	
    	TableRow row;
    	TextView t1, t2, t3;
    	//int rowId;
    	
    	// Clear the table. seemingly unnecessary steps below assure clearing of table, when 
    	// there is only one item left in the table.
		exercises_table.removeAllViewsInLayout();
		row = new TableRow(this);
		exercises_table.addView(row, new TableLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		
    	try {
    		workoutList = new ArrayList<Workout>(controller.getAllUserWorkouts());
    	} catch (Exception e){
    		Toast.makeText(this, "No workouts have been added.", Toast.LENGTH_LONG).show();
    		return;
    	}
    	
    	exercises_table.removeAllViewsInLayout();
		
    	// Sort the workout list by date
    	workoutList = controller.nameOrder(workoutList);
    	
    	
    	// Fill out the exercise history table    	
    	for (int i = 0; i < workoutList.size(); i++) {
    		row = new TableRow(this);
    		
    		t1 = new TextView(this);
    		t2 = new TextView(this);
    		t3 = new TextView(this);
    		
    		if( workoutList.get(i).getTitle().length() > 20 ){
    			t1.setText(workoutList.get(i).getTitle().substring(0, 20) + "... " );
    		}
    		else{ t1.setText(workoutList.get(i).getTitle() ); }
    		
    		// TODO: Convert the date from a long number to MM/DD/YYYY
    		t2.setText(workoutList.get(i).getDateReadable());
    		
    		// TODO: Convert time from seconds to HH:MM:SS
    		t3.setText(workoutList.get(i).getTimeReadable());
    		
    		//t1.setTextSize(20);
    		//t2.setTextSize(20);
    		
    		row.addView(t1);
    		row.addView(t2);
    		row.addView(t3);
    		
    		// Assign the loop counter value as a new id number for each row
    		row.setId(i);

    		exercises_table.addView(row, new TableLayout.LayoutParams(
    				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    		
    		row.setOnClickListener(new  OnClickListener() {
    			// Row was selected
    	        public void onClick(View v) {
    	            v.setBackgroundColor(Color.DKGRAY);
    	            displayWorkoutDetails(v.getId());
    	        }
    	    });
    	}
    	
    }
    
    /**
     * Displays the title, description, weight, time, and notes of a 
     * user-saved workout.
     * @param id id of the selected row
     */
    private void displayWorkoutDetails(int id) {
    	final int delLocation = id;
    	
    	/** To hold workout details */
		String workoutDetails = String.format
		("%s\n\nWeight: %s\nReps: %s\nTime: %s\n\n%s", 
				workoutList.get(id).getDescription(), 
				workoutList.get(id).getWeight(), 
				workoutList.get(id).getReps(),
				( workoutList.get(id).getTime() == 0 ? "": workoutList.get(id).getTimeReadable() ),
				( workoutList.get(id).getNotes() == null ? "": workoutList.get(id).getNotes() )
				);
    	
    	// Build an exercise description window to display
    	AlertDialog.Builder alertDialogBuilder = 
        				new AlertDialog.Builder(this);
        
        alertDialogBuilder.setTitle(workoutList.get(id).getTitle());
        alertDialogBuilder.setIcon(me.croute.calendarexample.R.drawable.eft);
        
     	alertDialogBuilder.setMessage(workoutDetails)
     					  .setNegativeButton("Close",new DialogInterface.OnClickListener() {
     						 public void onClick(DialogInterface dialog, int id) {
     							 // if this button is clicked, just close
     							 // the dialog box and do nothing
     							 dialog.cancel();
     						 }
     					 });
     	
     	alertDialogBuilder.setPositiveButton("Delete",new DialogInterface.OnClickListener() {
			 public void onClick(DialogInterface dialog, int i) {
				 	// if this button is clicked, just close
				 	// the dialog box and do nothing
				 	controller.deleteWorkout(workoutList.get(delLocation));
				 	fillExerciseTableSortedByName();
					dialog.cancel();
				 }
			 });
     	
     	alertDialogBuilder.setNeutralButton("Edit",new DialogInterface.OnClickListener() {
			 public void onClick(DialogInterface dialog, int i) {

					Workout w = workoutList.get(delLocation);
					
					Intent workoutUpdate = new Intent( getApplicationContext(), AddWorkout.class );
					
					workoutUpdate.putExtra(  "ID", w.getID());
					workoutUpdate.putExtra(  "Title", w.getTitle());
					workoutUpdate.putExtra(  "Description", w.getDescription());
					workoutUpdate.putExtra(  "Date", w.getDate());
					workoutUpdate.putExtra(  "Reps", w.getReps());	
					workoutUpdate.putExtra(  "Weight", w.getWeight());				
					workoutUpdate.putExtra(  "Time", w.getTime());	
					workoutUpdate.putExtra(  "Notes", w.getNotes());	
					
					startActivity(workoutUpdate);
					
				 }
			 });
      
     	// create alert dialog
     	AlertDialog alertDialog = alertDialogBuilder.create();
      
     	// show it
     	alertDialog.show();
    }
    
    
    /*public void function2(int id){  
        Toast.makeText(this, "function 2 called", Toast.LENGTH_LONG).show();  
    }*/ 
}